<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapboxLanguage from '@mapbox/mapbox-gl-language';
// import { getHistoryData } from './api/historyData';

import { RulerControl, ZoomControl } from 'mapbox-gl-controls';

import 'mapbox-gl-controls/lib/controls.css';

import { accAdd } from '../utils/calc';

export default {
  data() {
    return {
      // 历史数据
      historyData: null,
      // map 地图对象实例
      map: null,
    };
  },
  mounted() {
    this._createBaseMap();
  },
  methods: {
    _createBaseMap() {
      // 自己绘制的样式地图令牌
      mapboxgl.accessToken =
        'pk.eyJ1IjoiaW54bG54IiwiYSI6ImNsMzRmZDE4dTBhOWczaWs3a2psanphMnUifQ.iKIlYhNlW_13OqBJLOc9sw';

      const map = new mapboxgl.Map({
        container: 'app',
        antialias: true, // 抗锯齿
        style: 'mapbox://styles/mapbox/dark-v10',
        // style: mapStyle,
        center: [113.97923191113188, 22.589860256941634],
        zoom: 12,
      });

      // 汉化插件只能被调用一次
      if (mapboxgl.getRTLTextPluginStatus() === 'unavailable') {
        mapboxgl.setRTLTextPlugin(
          'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js',
          () => {}, // 发生错误时的回调函数
          true // Lazy load the plugin only when text is in arabic
        );
        // 设置为中文语言，热更新情况下失效
        const language = new MapboxLanguage({
          defaultLanguage: 'zh-Hans',
        });
        map.addControl(language);
      }

      this.map = map;
      window.map = map;

      // 启用右上角的控制按钮，放大，缩小，校正方向
      map.addControl(new mapboxgl.NavigationControl());
      // 测量标尺控制器 ======================================
      map.addControl(
        new RulerControl({
          units: 'kilometers',
          labelFormat: (n) => `${n.toFixed(2)} km`,
        }),
        'top-right'
      );
      map.on('ruler.on', () => console.log('ruler: on'));
      map.on('ruler.off', () => console.log('ruler: off'));
      // ====================================================

      map.addControl(new ZoomControl(), 'top-left');

      // var geometrySquare = {
      //   type: 'FeatureCollection',
      //   features: [
      //     {
      //       type: 'Feature',
      //       geometry: {
      //         type: 'Polygon',
      //         coordinates: [
      //           [
      //             [113.9, 22.6],
      //             [113.90679081005732, 22.599496188183466],
      //             [113.90610416455024, 22.588085146860493],
      //             [113.88790805859378, 22.58776815999103],
      //           ],
      //         ],
      //       },
      //     },
      //   ],
      // };

      function generateSquareGeoJson(
        squareSize,
        horizontalNumber,
        verticalNumber
      ) {
        // 起点经纬度
        const startLngLat = [113.9, 22.6];
        const geoInitTemplate = {
          type: 'FeatureCollection',
          features: [
            // {
            //   type: 'Feature',
            //   geometry: {
            //     type: 'Polygon',
            //     coordinates: [],
            //   },
            // },
          ],
        };
        // 将squareSize缩放100倍
        squareSize /= 100;
        // TODO:根据横向和纵向的值来生成方块
        for (let i = 0; i < horizontalNumber; i++) {
          for (let j = 0; j < verticalNumber; j++) {
            const feature = {
              type: 'Feature',
              geometry: {
                type: 'Polygon',
                coordinates: [[]],
              },
            };
            feature.geometry.coordinates[0] = generateSquare(
              squareSize,
              accAdd(startLngLat[0], squareSize * (j + 1)),
              accAdd(startLngLat[1], squareSize * (i + 1))
            );
            geoInitTemplate.features.push(feature);
          }
        }

        /**
         * 生成一个小的正方形的经纬度
         */
        function generateSquare(squareSize, startLng, startLat) {
          const squareArr = new Array(4);
          // const len = squareArr.length;
          squareArr[0] = [startLng, startLat];
          squareArr[1] = [accAdd(startLng, squareSize), startLat];
          squareArr[2] = [
            accAdd(startLng, squareSize),
            accAdd(startLat, squareSize),
          ];
          squareArr[3] = [startLng, accAdd(startLat, squareSize)];
          return squareArr;
        }
        return geoInitTemplate;
      }

      const geoJson = generateSquareGeoJson(20, 10, 10);
      console.log('geoJson :>> ', geoJson);
      map.on('load', function () {
        map.addLayer({
          id: 'square',
          type: 'fill',
          source: {
            type: 'geojson',
            data: geoJson,
          },
          paint: {
            'fill-color': 'red',
            'fill-opacity': 0.5,
            'fill-outline-color': 'white',
          },
        });
      });

      // zoom变化时打印zoom值
      map.on('zoom', function (e) {
        console.log(e.target.getZoom());
      });

      map.on('click', function (e) {
        console.log('e.lngLat :>> ', e.lngLat);
      });
    },
  },
  beforeDestroy() {
    this.map.remove();
    this.map = null;
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}
#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}

/* 将底部的logo和信息声明隐藏 */
.mapboxgl-ctrl-logo {
  display: none !important;
}
.mapboxgl-ctrl-bottom-right {
  display: none !important;
}
</style>
